/**
 * Project Name:fastPlat
 * File Name:ArticleServiceImpl.java
 * Package Name:com.fast.cms.service.article
 * Date:2014年12月17日下午1:48:41
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 *
*/

package com.fast.cms.service.article.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fast.base.dao.daoSuport.JpaDaoSupport;
import com.fast.base.generator.BaseProcess;
import com.fast.base.generator.HtmlGenerator;
import com.fast.base.db.sql.AbstractSqlGenerator;
import com.fast.base.db.sql.impl.SqlGeneratorImpl;
import com.fast.base.util.DateUtils;
import com.fast.base.util.LogUtils;
import com.fast.base.util.PropertiesUtils;
import com.fast.base.util.data.MathUtils;
import com.fast.base.db.page.PageView;
import com.fast.base.db.page.QueryResult;
import com.fast.cms.constant.CheckStatusEnum;
import com.fast.cms.model.article.Article;
import com.fast.cms.model.article.NoticeInfo;
import com.fast.cms.model.article.SiteMsg;
import com.fast.cms.model.system.Dictionary;
import com.fast.cms.service.article.ArticleService;
import com.fast.cms.web.form.ArticleListForm;
import com.fast.cms.web.form.CheckArticleForm;
import com.fast.user.model.admin.AdminUser;
import com.fast.user.model.admin.Group;

/**
 * ClassName:ArticleServiceImpl <br/>
 * 用途: 文章服务  <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  
 * @since    JDK 1.6
 * @see
 * Date:     2014年12月17日 下午1:48:41 <br/> 	 
 */
@Service("articleService")
public class ArticleServiceImpl extends JpaDaoSupport implements ArticleService {
	
	/**
	 * 新增阅读量
	 * @param id
	 */
	public void updateReadCount(int id){
		String sql = "update Article set readCount=readCount+1 where id="+id;
		super.entityManager.createQuery(sql).executeUpdate();
	}
	
	/**
	 * 作用：查询文章列表<br/>
	 */
	public List<Article> getArticleList(){
		return this.queryForBeanList(Article.class, "where 1=1");
	}
	
	/**
	 * 分页获取文章列表
	 * @return PageView<Article>
	 */
	@Override
	public PageView<Article> getArticleList(ArticleListForm articleListForm){
		StringBuffer sb = new StringBuffer(" where 1=1 ");
		sb.append("and status="+articleListForm.getStatus()+" ");
		sb.append("and delete_flag="+articleListForm.getDeleteFlag()+" ");
		
		int adminId = Integer.parseInt(articleListForm.getCurUserId());
		boolean isSubUser = this.isSubUserForArticle(adminId);
		
		String articleTypeObj = articleListForm.getArticleTypeObj();
		if(StringUtils.isNotEmpty(articleTypeObj)){
			JSONObject typeJson = JSONObject.parseObject(articleTypeObj.replace("&quot;", "\""));
			String typeId = typeJson.getString("code");
			sb.append(" and articleTypeId="+typeId+" ");
		}
		
		if(StringUtils.isNotEmpty(articleListForm.getArticleTitile())){
			sb.append(" and articleTitile like '%"+articleListForm.getArticleTitile()+"%' ");
		}
		
		if(StringUtils.isNotBlank(articleListForm.getSaveType())){
			sb.append(" and saveType="+articleListForm.getSaveType());
		}
		
		
		if(!isSubUser){
			if(StringUtils.isNotEmpty(articleListForm.getCheckStatus())){
				sb.append(" and checkStatus='"+articleListForm.getCheckStatus()+"' or creater_id="+articleListForm.getCurUserId()+" ");
			}else{
				sb.append(" and checkStatus='"+CheckStatusEnum.agree.getCode()+"' or creater_id="+articleListForm.getCurUserId()+" ");
			}
			
		}else{
			if(StringUtils.isNotEmpty(articleListForm.getCheckStatus())){
				sb.append(" and checkStatus="+articleListForm.getCheckStatus()+" ");
			}
		}
		
		if(StringUtils.isNotEmpty(articleListForm.getArticleTypeId())){
			String articleTypeId = articleListForm.getArticleTypeId();
			int count = super.count(Dictionary.class, " where parentUUID='"+articleTypeId+"'");
			if(count>0){
				List<Dictionary> dicList = super.queryForBeanList(Dictionary.class, " where parentUUID='"+articleTypeId+"'");
				StringBuffer typeSb = new StringBuffer("'"+articleTypeId+"',");
                for (Dictionary dictionary : dicList) {
                	typeSb.append("'"+dictionary.getUuid()+"',");
				}
                typeSb.deleteCharAt(typeSb.lastIndexOf(","));
				sb.append("and articleTypeId in("+typeSb.toString()+") ");
                
			}else{
				sb.append("and articleTypeId='"+articleListForm.getArticleTypeId()+"' ");
			}
		}
		String ordersql = " order by edit_time desc ";
		QueryResult<Article>  queryResult = super.queryForBeanListByPage(Article.class,sb.toString(),ordersql,(articleListForm.getPage()-1)*articleListForm.getRows(),articleListForm.getRows());
		PageView<Article> pageView = new PageView<Article>();
	    pageView.setCurrentPage(articleListForm.getPage());
		pageView.setQueryResult(queryResult);
 		return pageView;
	}
	
	/**
	 * @Title: isSubUserForArticle 
	 * @Description: 判断当前用户是否为审核用户
	 * @param adminId
	 * @return 
	 * @throws
	 * @developer:LUSHUIFA242
	 * @date 2017年11月7日 下午4:04:06
	 */
	private boolean isSubUserForArticle(int adminId) {
		try {
			AdminUser adminUser = super.queryForBeanById(AdminUser.class, adminId);
			Group group = super.queryForBean(Group.class, " where id="+adminUser.getGroupId());
			String groupArray = group.getPermissionArray();
			if(groupArray.contains("[PA0B2C1E2E]:审核")||adminUser.getUserName().contains("kaifa")){
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			LogUtils.error("isSubUserForArticle err:", e);
			return false;
		}
	}

	/**
	 * 生成静态页面
	 * @param article
	 */
	@Override
	public void genArticleDetailHtmlPage(Article article) {
		String templateDir = BaseProcess.getFrontFtlPath()+"ftl/";
		String templateFile = "articleDetail.ftl";
		String htmlFileDir = PropertiesUtils.getCoreContextProperty("fileDisk")+"/articleHtml";
		String htmlFile = article.getUuid()+".html";
		String basePath = PropertiesUtils.getCoreContextProperty("basePath");
		Map<String,Object> dataModel = new HashMap<String,Object>();
		dataModel.put("article", article);
		dataModel.put("basePath",basePath);
		HtmlGenerator.geneHtmlFile(templateDir, templateFile, dataModel, htmlFileDir, htmlFile);
	}
	
	/**
	 * 批量生成静态页面
	 * @param article
	 */
	@Override
	public void batchGenArticleDetailHtmlPage(List<Article> articleList) {
		try {
			Thread localThread = new Thread(){
				@Override
				public void run() {
					for(Article article:articleList){
						String templateDir = BaseProcess.getFrontFtlPath()+"ftl/";
						String templateFile = "articleDetail.ftl";
						String htmlFileDir = PropertiesUtils.getCoreContextProperty("fileDisk")+"/articleHtml";
						String htmlFile = article.getUuid()+".html";
						String basePath = PropertiesUtils.getCoreContextProperty("basePath");
						Map<String,Object> dataModel = new HashMap<String,Object>();
						dataModel.put("article", article);
						dataModel.put("basePath",basePath);
						HtmlGenerator.geneHtmlFile(templateDir, templateFile, dataModel, htmlFileDir, htmlFile);
					}
				}
			};
			localThread.start();
		} catch (Exception e) {
			LogUtils.error("batchGenArticleDetailHtmlPage生成静态页面异常", e);
		}
	}
	
	/**
	 * 将所有文章生成静态页面
	 * @param article
	 */
	@Override
	public void batchGeAllArticleHtmlPage() {
		try {
			List<Article> articleList = super.queryForBeanList(Article.class, "where 1=1");
			Thread localThread = new Thread(){
				@Override
				public void run() {
					for(Article article:articleList){
						String templateDir = BaseProcess.getFrontFtlPath()+"ftl/";
						String templateFile = "articleDetail.ftl";
						String htmlFileDir = PropertiesUtils.getCoreContextProperty("fileDisk")+"/articleHtml";
						String htmlFile = article.getUuid()+".html";
						String basePath = PropertiesUtils.getCoreContextProperty("basePath");
						Map<String,Object> dataModel = new HashMap<String,Object>();
						dataModel.put("article", article);
						dataModel.put("basePath",basePath);
						HtmlGenerator.geneHtmlFile(templateDir, templateFile, dataModel, htmlFileDir, htmlFile);
					}
				}
			};
			localThread.start();
		} catch (Exception e) {
			LogUtils.error("batchGenArticleDetailHtmlPage生成静态页面异常", e);
		}
	}
	
	/**
	 * 查询资讯列表，并限制数量
	 * 只查审批通过的数据
	 * @param articleTypeId 资讯分类
	 * @param limitSize 限制数量
	 * @param selectType
	 * @return
	 */
	@Override
	@Cacheable(value="articleCache",key="'getArticleListForLimit'+#articleTypeId+'_'+#limitSize+'_'+#selectType")
	public List<Map<String, Object>> getArticleListForLimit(String articleTypeId, int limitSize, String selectType) {
		StringBuffer sb = new StringBuffer(" where 1=1 ");
		//查出没有回收的数据
		sb.append(" and delete_flag=0 ");
		//查出没有屏蔽的数据
		sb.append(" and status=1 ");
		//查出审批通过的数据
		sb.append(" and checkStatus='"+CheckStatusEnum.agree.getCode()+"' ");
		if(!articleTypeId.equals("")){
			int count = super.count(Dictionary.class, " where parentUUID='"+articleTypeId+"'");
			if(count>0){
				List<Dictionary> dicList = super.queryForBeanList(Dictionary.class, " where parentUUID='"+articleTypeId+"'");
				StringBuffer typeSb = new StringBuffer("'"+articleTypeId+"',");
                for (Dictionary dictionary : dicList) {
                	typeSb.append("'"+dictionary.getUuid()+"',");
				}
                typeSb.deleteCharAt(typeSb.lastIndexOf(","));
				sb.append("and articleTypeId in("+typeSb.toString()+") ");
			}else{
				sb.append("and articleTypeId='"+articleTypeId+"' ");
			}
		}
		
		if(!selectType.equals("")){
			if(selectType.equals("newest")){
				sb.append(" order by edit_time desc ");
			}else if(selectType.equals("clickRate")){
				sb.append(" order by readCount desc ");
			}
		}else{
			sb.append(" order by edit_time desc ");
		}
		sb.append(" limit 0,"+limitSize);
		String wheresql = sb.toString();
		String queryFields = "id,uuid,articleTitile,content,imageUrl,columnName,articleType,date_format(edit_time,'%Y-%m-%d %H:%I:%S')  as editTime ";
		String sql = "select "+queryFields+" from "+AbstractSqlGenerator.getTableName(Article.class)+" "+wheresql;
		List<Map<String,Object>> articleList = super.queryForMapList(sql);
		return articleList;
	}
	
	/**
	 * 保存与更新
	 * @param article
	 * @return
	 */
	@CacheEvict(cacheNames={"articleCache"},allEntries=true)
	public Article saveOrUpdateArticle(Article article){
		return super.merge(article);
	}

	/**
	 * 审批文章
	 */
	@CacheEvict(cacheNames={"articleCache"},allEntries=true)
	public boolean checkArticle(CheckArticleForm checkArticleForm) {
		int checkStatus = checkArticleForm.getCheckStatus();
		String checkMsg = checkArticleForm.getCheckMsg();
		StringBuffer sql = new StringBuffer("");
		sql.append("update "+SqlGeneratorImpl.getTableName(Article.class)+" set ");
		sql.append(" checkerId="+checkArticleForm.getCheckerId()+",");
		sql.append(" checker='"+checkArticleForm.getChecker()+"',");
		sql.append(" checkStatus="+checkStatus+",");
		sql.append(" checkDt='"+DateUtils.getNow()+"',");
		sql.append(" checkMsg='"+checkMsg+"' ");
		sql.append(" where id="+checkArticleForm.getId()+"");
		boolean actionFlag = super.modifyRow(sql.toString())>0;
		if(actionFlag){
			int id = checkArticleForm.getId();
			//0为待审核,1为已审核确认,2为审核末通过
			Article article = super.queryForBeanById(Article.class, id);
			//增加信息
			String title = "资讯编号【"+article.getUuid()+"】"+CheckStatusEnum.getName(checkArticleForm.getCheckStatus());
			String reciveAdminArr = "["+article.getCreaterId()+":"+article.getCreater()+"]";
			String msgDetail = "资讯标题["+article.getArticleTitile()+"] 审批状态为:"+
			CheckStatusEnum.getName(checkArticleForm.getCheckStatus())+
			" 批阅信息为："+checkArticleForm.getCheckMsg()+" 审批人为："+
			checkArticleForm.getChecker()+" 审批时间为："+DateUtils.getNow();
			SiteMsg siteMsg = new SiteMsg(title,"审批信息",reciveAdminArr, msgDetail);
			siteMsg.setUuid(MathUtils.getTheOnlyStr());
			super.merge(siteMsg);
		}
		return actionFlag;
	}
	
	/**
	 * 查询待审批的数据和
	 * @param adminId
	 * @return
	 */
	public int queryCheckArticleCount(int adminId){
		if(isSubUserForArticle(adminId)){
			return  super.count(Article.class, " where checkStatus=0  and delete_flag=0");
		}else{
			return 0;
		}
	}
}
